import { useEffect, useState } from 'react';
import { BackIcon } from '@/components/icons';

// 加深关键词
const StyledResult = ({ value, keyWord }) => {
   const values = value.split('');
   return (
      <div>
         {values.map((word, index) => {
            if (keyWord.includes(word)) {
               return (
                  <span className="color-main" key={index}>
                     {word}
                  </span>
               );
            }
            return word;
         })}
      </div>
   );
};

type Props = {
   initValue?: string;
   map: any; //地图传过来的接口
   onSelect?: (any) => void;
   onClose: () => void;
};

const Search = ({ initValue = '', map, onSelect, onClose }: Props) => {
   const [value, setValue] = useState(initValue); // 初始关键词
   const [results, setResults] = useState([]); // 搜索结果
   const [hasNextPage, setHasNextPage] = useState(false); // 是否能获取更多
   const [tips, setTips] = useState([]); // 提示列表, 用于追加关键词
   const [type, setType] = useState('address'); // 显示类型 address| 具体结果；tip | 追加关键词

   // 更改关键词
   const handleChangeKeyWord = (e) => {
      const { value } = e.target;
      setValue(value);
   };

   // 搜索
   const handleSearch = async (keyword) => {
      const { list, hasNextPage, type } = await map.searchPlace(keyword);
      setHasNextPage(hasNextPage);
      setType(type);
      if (type === 'address') {
         setResults(list);
      } else {
         setTips(list);
      }
   };

   // 追加关键词
   const handleSelectTip = (item) => {
      const keyword = `${item.name}${value}`;
      setValue(keyword);
      handleSearch(keyword);
   };

   useEffect(() => {
      // 监听是否获取下一页数据
      const element = document.getElementById('scrollable-element');
      if (element) {
         const observer = new IntersectionObserver(
            async (entries) => {
               const [entry] = entries;
               if (entry.isIntersecting) {
                  const { list, hasNextPage } = await map.searchNextPage();
                  setResults((pre) => [...pre, ...list]);
                  setHasNextPage(hasNextPage);
               }
            },
            { threshold: 1.0 }
         );
         observer.observe(element);

         () => {
            observer.unobserve(element);
         };
      }
   }, [hasNextPage]);

   return (
      <div className="bg-white p-2 top-0 bottom-0 left-0 right-0 absolute">
         <div className="flex bg-zinc-100 items-center space-x-1 p-2">
            <BackIcon onClick={onClose} />
            <input
               className="grow"
               value={value}
               onChange={handleChangeKeyWord}
            />
            <div
               className="color-main"
               onClick={handleSearch.bind(null, value)}
            >
               搜索
            </div>
         </div>
         <div className="h-[calc(100%_-_44px)] overflow-auto pr-2">
            {type === 'address' &&
               results.map((item) => (
                  <div
                     key={item.id}
                     className="mb-2"
                     onClick={onSelect.bind(null, item)}
                  >
                     <StyledResult value={item.name} keyWord={value} />
                     <div className="space-x-2 text-xs color-disabled">
                        <span>{item.address}</span>
                        <span>{item.type.split(';')[0]}</span>
                     </div>
                  </div>
               ))}
            {type === 'tip' && (
               <>
                  <div className="color-disabled my-2">请选择范围：</div>
                  {tips.map((item, index) => (
                     <div
                        key={index}
                        className="mb-2"
                        onClick={handleSelectTip.bind(null, item)}
                     >
                        {item.name}
                     </div>
                  ))}
               </>
            )}
            {hasNextPage && (
               <div
                  className="my-4 color-disabled text-sm text-center"
                  id="scrollable-element"
               >
                  加载中...
               </div>
            )}

            {results.length > 12 && !hasNextPage && (
               <div
                  className="my-4 color-disabled text-sm text-center"
                  id="scrollable-element"
               >
                  没有更多了
               </div>
            )}
         </div>
      </div>
   );
};

export default Search;
